<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    title="选择资产类型"
    width="750px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-table
      ref="dataTableRef"
      :data="tableData"
      :row-key="(row) => row.id"
      highlight-current-row
      border
      :tree-props="{
        children: 'nodes',
        hasChildren: 'hasChildren',
      }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资产类型名称" prop="assetTypeName" />
      <el-table-column label="资产类型编号" prop="assetTypeCode" />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          :disabled="selectedIds.length === 0"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import useEvent from "@/utils/useEvent"; // 引入
const dictionaryStore = useDictStoreHook();

const { eventBusOn, eventBusEmit } = useEvent();
defineOptions({
  name: "EAMFAULTSYSTEMMANAGEMODEASSETDIALOG",
  inheritAttrs: false,
});
const loading = ref(false);
const visible = ref(false);
const tableData = ref([]);
const selectedIds = ref([]);
const faultModeId = ref("");

const props = defineProps({
  assetKind: {
    type: Number,
    default: 1,
  },
});

const getTableData = async (faultModeId: string) => {
  const { data } = await request({
    url: "/eam/eamCommon/getAvailableTree",
    method: "post",
    data: { faultModeId, assetKind: props.assetKind },
  });
  tableData.value = data;
};
const handleSelectionChange = (selection: any) => {
  selectedIds.value = selection.map((item: any) => item.id);
};

onMounted(() => {
  eventBusOn("modeAsset", async ({ param }) => {
    await getTableData(param);
    visible.value = true;
    faultModeId.value = param;
  });
});
const handleSubmit = async () => {
  loading.value = true;
  await request({
    url: "/eam/eamfaultmodeasset/saveBatch",
    method: "post",
    data: selectedIds.value.map((item: string) => ({
      faultModeId: faultModeId.value,
      assetTypeId: item,
      assetKind: props.assetKind,
    })),
  })
    .then(() => {
      closeDialog();
      eventBusEmit("closeModeAssetDialog");
    })
    .finally(() => {
      loading.value = false;
    });
};
const closeDialog = () => {
  visible.value = false;
  faultModeId.value = "";
  selectedIds.value = [];
  tableData.value = [];
};
</script>
